#include "link_stack.h"

void stack_create(stack **S)
{
    (*S) = (stack *)malloc(sizeof(stack));
    (*S)->data = 0;
}

void stack_push(stack *S, int data)
{
    if (NULL == S) {
        printf("无效栈\n");
        return ;
    }

    stack *new = (stack *)malloc(sizeof(stack));
    new->data = data;

    new->next = S->next;
    S->next = new;
}

int stack_pop(stack *S)
{
    if (NULL == S) {
        printf("无效栈\n");
        return -1;
    }

    if (S->next == NULL) {
        printf("空栈\n");
        return -1;
    }

    stack *tmp = S->next;
    int data = S->next->data;
    S->next = tmp->next;
    free(tmp);

    return data;
}

void link_stack_destroy(stack **S)
{
    if (NULL == *S) {
        printf("空栈.\n");
        return ;
    }

    stack *tmp;

    while ((*S)->next != NULL) {
        tmp = *S;
        (*S) = (*S)->next;
        free(tmp);
    }

    free(*S);
    *S = NULL;
}

void link_stack_empty(stack **S) {
    if (NULL == *S) {
        printf("无效栈\n");
        return ;
    }
#if 0
    stack *tmp = *S;

    while((*S)->next != NULL) {
        tmp = *S;
        *S = (*S)->next;
        free(tmp);
    }
#endif
    stack *tmp;

    while((*S)->next != NULL) {
        tmp = (*S)->next;
        (*S)->next = tmp->next;
        free(tmp);
    }
}

int link_stack_top(stack *S) {
    if (is_empty(S)) {
        printf("无栈顶元素");
        return -1;
    }

    return S->next->data;
}

int is_empty(stack *S) {
    if (NULL == S) {
        printf("无效栈.\n");
        return -1;
    }

    return S->next == NULL ? 1 : 0;
}

